package com.dtranx.tools.corpora.ability.search;

import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import com.dtranx.tools.corpora.ability.constants.EsConstants;
import com.dtranx.tools.corpora.ability.vo.MatchingVo;
import com.dtranx.tools.corpora.abilityapi.enums.SearchMode;
import com.google.common.collect.Lists;

import java.util.List;

/**
 *
 * 包含匹配+模糊匹配（主要用于搜索功能）
 *
 * @ClassName VagueSearchAndSearchModeSearch
 * @Description TODO
 * @Date 2024/8/21 14:36
 * @Author ly
 **/
public class VagueSearchAndSearchModeSearch extends AbstractModeSearch {


    @Override
    public void buildQueryBuilder0(BoolQuery.Builder queryBuilder, MatchingVo matchingVo) {
//        queryBuilder.filter(generateQueries0(matchingVo,matchingVo.getValue()));
//        List<Query> queries = generateQueries(matchingVo, matchingVo.getValue());
//        //基础上再增加一个matchPhrase
//        queries.add(generateMatchPhraseQuery(matchingVo, matchingVo.getValue()));
        queryBuilder.should(generateQueries0(matchingVo,matchingVo.getValue()));
        queryBuilder.minimumShouldMatch(EsConstants.MINIMUM_SHOULD_MATCH);
    }

    @Override
    protected List<Query> generateQueries0(MatchingVo matchingVo, String value) {
//        String fuzzy = StringUtils.isEmpty(matchingVo.getFuzzy()) ? EsConstants.DEFAULT_FUZZY : matchingVo.getFuzzy();
        List<Query> shouldQueries = Lists.newArrayList();
        // 完全匹配
        matchingVo.setBoost(10f);
        shouldQueries.add(termQuery(matchingVo, value));
        // 短语匹配
        matchingVo.setBoost(8f);
        shouldQueries.add(matchPhraseQuery(matchingVo, value));
        // 分词匹配 词项全部匹配
        matchingVo.setBoost(5f);
        matchingVo.setFuzzy(EsConstants.ALL_MINIMUM_SHOULD_MATCH);
        shouldQueries.add(matchQuery(matchingVo, value));
        // 分词匹配 词项部分匹配
        matchingVo.setBoost(3f);
        matchingVo.setFuzzy(EsConstants.DEFAULT_FUZZY);
        shouldQueries.add(matchQuery(matchingVo, value));
        return shouldQueries;
//        List<Query> queries = Lists.newArrayList(Query.of(query -> query.bool(boolBuilder -> boolBuilder.should(shouldQueries))));
//        if (BooleanUtils.isTrue(matchingVo.getFlag())) {
//            queries.add(buildLenFilter(matchingVo, value));
//        }
    }

    @Override
    public SearchMode getMode() {
        return SearchMode.VAGUE_SEARCH_AND_SEARCH;
    }

    @Override
    protected String getScript() {
        return EsConstants.EDIT_DISTANCE_ES_SCORE_AND_MATCH_SCRIPT;
    }
}
